﻿namespace WXWorkSvc.Common.TagHelpers;
[HtmlTargetElement("wx-list", TagStructure = TagStructure.WithoutEndTag)]
public class WxListTagHelper : TagHelper
{
    //const string propertyPrefix = "Items[0].";

    private readonly Dictionary<string, object> _ItemValues = new();

    [HtmlAttributeNotBound]
    [ViewContext]
    public ViewContext ViewContext { get; set; } = default!;
    private readonly IHtmlGenerator _HtmlGenerator;
    public WxListTagHelper(IHtmlGenerator generator)
    {
        _HtmlGenerator = generator;
    }

    #region Properties
    [HtmlAttributeName("asp-items")]
    public ModelExpression Items { get; set; } = default!;
    [HtmlAttributeName(DictionaryAttributePrefix = "asp-for-")]
    public Dictionary<string, ModelExpression> Fors { get; set; } = new();
    [HtmlAttributeName("wx-extra")]
    public ModelExpression Extra { get; set; } = default!;

    [HtmlAttributeName("asp-page")]
    public string PageName { get; set; } = default!;
    /// <summary>
    /// 常量参数
    /// </summary>
    [HtmlAttributeName(DictionaryAttributePrefix = "asp-const-")]
    public Dictionary<string, object> ConstValues { get; set; } = new();
    [HtmlAttributeName(DictionaryAttributePrefix = "asp-route-")]
    public Dictionary<string, ModelExpression> RouteValues { get; set; } = new();
    #endregion
    private TagBuilder GenerateWXLink(ModelExplorer itemModelExplorer)
    {
        var routeValues = new Dictionary<string, object>();
        foreach (var kv in ConstValues)
            routeValues.Add(kv.Key, kv.Value);// itemModelExplorer.GetModelValue(_ItemValues, kv.Value.Metadata.Name!));


        foreach (var kv in RouteValues)
            routeValues.Add(kv.Key, itemModelExplorer.GetModelValue(_ItemValues, kv.Value.Metadata.Name!));

        return _HtmlGenerator.GeneratePageLink(ViewContext, "", PageName, null, null, null, null, routeValues, new { @class = TagHelperExtend.WeuiCellLinkClass });
    }
    /// <summary>
    /// 简单List
    /// </summary>
    /// <param name="output"></param>
    private void WXProcess(TagHelperOutput output)
    {
        output.Attributes.Add("class", "weui-cells");
        var propertyName = Fors.First().Value.Metadata.Name!;
        foreach (var item in (IList)Items.Model)
        {
            _ItemValues.Clear();
            var itemModelExplorer = Items.ModelExplorer.GetExplorerForModel(item);
            var title = itemModelExplorer.GetModelValue(_ItemValues, propertyName);

            var linkTagBuilder = GenerateWXLink(itemModelExplorer);
            linkTagBuilder.InnerHtml.SetHtmlContent(string.Format(TagHelperExtend.WeuiCellLinkText, title));
            output.Content.AppendHtml(linkTagBuilder);

        }
    }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        if (string.IsNullOrEmpty(PageName))
            throw new Exception("wx-list的asp-page不能为空");
        output.TagName = "div";
        output.TagMode = TagMode.StartTagAndEndTag;
        if (Fors.Count == 1)
        {
            WXProcess(output);
            return;
        }
        var forKeys = Fors.Keys.ToList();

        output.Attributes.Add("class", TagHelperExtend.WeuiMediaLinkDivMainClass);

        var div2TagBuilder = new TagBuilder("div");
        div2TagBuilder.AddCssClass(TagHelperExtend.WeuiMediaLinkDivSecondaryClass);
        div2TagBuilder.Attributes.Add("style", TagHelperExtend.WeuiMediaLinkDivSecondarySytle);
        foreach (var item in (IList)Items.Model)
        {
            _ItemValues.Clear();
            var itemModelExplorer = Items.ModelExplorer.GetExplorerForModel(item);
            StringBuilder sbUl = new StringBuilder();
            for (int i = 1; i < forKeys.Count; i++)
            {

                var info = itemModelExplorer.GetModelValue(_ItemValues, Fors[forKeys[i]].Metadata.Name!);
                if (!int.TryParse(forKeys[i], out _))
                    info += " " + forKeys[i];
                sbUl.AppendFormat(TagHelperExtend.WeuiMediaLinkInfoFormat, info);
            }
            if (Extra is not null)
            {
                var extra = itemModelExplorer.GetModelValue(_ItemValues, Extra.Metadata.Name!);
                sbUl.AppendFormat(TagHelperExtend.WeuiMediaLinkExtraFormat, extra);
            }

            var linkTagBuilder = GenerateWXLink(itemModelExplorer);
            var title = itemModelExplorer.GetModelValue(_ItemValues, Fors[forKeys[0]].Metadata.Name!);
            if (!int.TryParse(forKeys[0], out _))
                title += " " + forKeys[0];
            linkTagBuilder.InnerHtml.SetHtmlContent(string.Format(TagHelperExtend.WeuiMediaLinkTextFormat, title, sbUl));

            div2TagBuilder.InnerHtml.AppendHtml(linkTagBuilder);
        }

        output.Content.SetHtmlContent(div2TagBuilder);
    }

    //private object GetModelValue(ModelExplorer modelExplorer, string propertyName)
    //{
    //    if (_ItemValues.TryGetValue(propertyName, out var existedValue))
    //        return existedValue;
    //    if (propertyName.StartsWith(propertyPrefix))
    //        propertyName = propertyName.Substring(propertyPrefix.Length);
    //    var index = propertyName.IndexOf(".");
    //    if (index == -1)
    //    {
    //        modelExplorer = modelExplorer.GetExplorerForProperty(propertyName);
    //        object? value = (modelExplorer.Model is bool b) ? (b ? "是" : "否") : modelExplorer.Model;
    //        _ItemValues.Add(propertyPrefix + propertyName, value);
    //        return value;
    //    }
    //    modelExplorer = modelExplorer.GetExplorerForProperty(propertyName.Substring(0, index));
    //    return GetModelValue(modelExplorer, propertyName.Substring(index + 1));
    //}
}
